/*
** main.c for malloc in /home/peelou/SVN/Malloc
** 
** Made by gery baudry
** Login   <baudry_g@epitech.net>
** 
** Started on  Mon Feb  4 13:52:58 2013 gery baudry
** Last update Fri Feb  8 16:15:22 2013 Maxime Wojciak
*/
#include	"malloc.h"
#include	<stdio.h>

t_malloc		*g_base = NULL;

static t_malloc	*go_to_empty()
{
  t_malloc		*ptr;

  ptr = g_base;
  while (ptr->next != NULL)
    ptr = ptr->next;
  return (ptr);
}

static void		*my_sbrk_tmp(t_malloc *tmp, t_malloc *tmp2, unsigned int size)
{
  tmp2 = sbrk(0);
  if (sbrk(SIZE_STRUCT + size) == (void*) - 1)
    return (NULL);
  tmp2->size = size;
  tmp2->next = NULL;
  tmp2->prev = tmp;
  return (tmp2);
}

static void		*my_sbrk(t_malloc *tmp, unsigned int size)
{
  t_malloc		*tmp2;
  tmp2 = NULL;
  if (!tmp)
    {
      tmp2 = sbrk(0);
      if (sbrk(SIZE_STRUCT + size) == (void*) - 1)
	return (NULL);
      tmp2->size = size;
      tmp2->next = NULL;
      tmp2->prev = NULL;
      tmp2->etat = 1;
      return (tmp2);
    }
  else
    return (tmp2 = my_sbrk_tmp(tmp, tmp2, size));
  tmp->etat = 0;
  return (tmp2);
}

void		*malloc(size_t size)
{
  t_malloc		*tmp;
  if (g_base)
    {
      tmp = g_base;
      tmp = go_to_empty();
      tmp = my_sbrk(tmp, size);
      g_base = tmp;
      return (tmp + 1);
    }
  else
    {
      tmp = g_base;
      tmp = my_sbrk(tmp, size);
      g_base = tmp;
      return (tmp + 1);
    }
  if (!tmp)
    return(NULL);
}
